package com.uam.core.business.help;


import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;


/**
 * @author wangbing wbbeijing@aliyun.com
 * @version 1.0.0
 * @date 2024-02-22
 * @description 经纬度坐标辅助工具
 */
@Component
public class CoordUtil {
    public static final String COMMA = ",";
    public static final double EARTH_RADIUS = 6378137.0;

    public static Coordinate[] convertListToArray(List<Coordinate> coordinatesList) {
        Coordinate[] coordinatesArray = new Coordinate[coordinatesList.size()];
        int i = 0;
        for (Coordinate coordinate : coordinatesList) {
            coordinatesArray[i++] = coordinate;
        }
        return coordinatesArray;
    }


    /**
     * 计算两坐标点之间的距离
     * @param startPoint 起点坐标
     * @param endPoint 终点坐标
     * @return double
     */
    public static Double pointDistance(String startPoint,String endPoint){
        String[] lonLatStart = StringUtils.tokenizeToStringArray(startPoint, COMMA);
        String[] lonLatEnd = StringUtils.tokenizeToStringArray(endPoint,COMMA);
        return calculateDistance(Double.valueOf(lonLatStart[1]),Double.valueOf(lonLatStart[0]),Double.valueOf(lonLatEnd[1]),Double.valueOf(lonLatEnd[0]));
    }

    /**
     * 计算两坐标点之间的距离
     * @author wangbing wbbeijing@aliyun.com
     * @date 2024/3/4
     * @param lat1 起点纬度
     * @param lon1 起点经度
     * @param lat2 终点纬度
     * @param lon2 终点经度
     * @return double
     */
    public static double calculateDistance(Double lat1, Double lon1, Double lat2, Double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return EARTH_RADIUS * c;
    }


}
